package cpre556.project2.eclipsePlugin.support;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import org.eclipse.core.runtime.Platform;

/**
 * Class that handles where files are saved
 * @author Eric
 */
public class Saver {
	/**
	 * Source file
	 */
	private String source;
	
	/**
	 * Plug-in being used
	 */
	private String type;
	
	/**
	 * Output from plug-in as a text file
	 */
	private String output;
	
	/**
	 * Executable location
	 */
	private String exe;
	
	/**
	 * The number of lines of code.
	 */
	private int lines = 0;
	
	/**
	 * Constructor
	 * @param source The source file being read
	 */
	public Saver(String source){
		init(source);
	}
	
	/**
	 * Initialized the class, called from constructor
	 * @param source Source file
	 */
	private void init(String source){
		this.source = source;
		
		try{
			BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(source)));
			
			int count = 0;
			while(in.readLine() != null){
				count++;
			}
			
			this.setLines(count);
		} 
		catch (FileNotFoundException e) {
			e.printStackTrace();
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
		
		outputFile();
	}
	
	/**
	 * Set the type variable
	 * @param type
	 */
	public void setType(String type){
		this.type = type;
	}
	
	/**
	 * Get the xml filename
	 * @return
	 */
	public String getFile(){
		return output + type + ".xml";
	}
	
	/**
	 * Get the ignored xml filename
	 * @return
	 */
	public String getIgnore(){
		return output + type + ".ignore.xml";
	}
	
	/**
	 * Get the output text filename
	 * @return
	 */
	public String getTxt(){
		return output + "output.txt";
	}
	
	/**
	 * Get the source filename
	 * @return
	 */
	public String getSource(){
		return source;
	}
	
	/**
	 * Get the output's filename
	 * @param output
	 * @return
	 */
	private void outputFile(){
		String workspace = Platform.getInstanceLocation().getURL().toString();
		workspace = workspace.substring(6, workspace.length());
		
		String project = source.replace(workspace, "");
		
		// Check to see if it's not located in the ssvchecker folder already
		if(!source.startsWith(workspace + "ssvchecker/")){
			output = workspace + "ssvchecker/" + project + "/";
		}
		else{
			output = source;
		}
		
		// Create the folder structure
		if(!(new File(output)).exists())
			(new File(output)).mkdirs();
	}
	
	/**
	 * Set executable file
	 * @param exe
	 */
	public void setExe(String exe) {
		this.exe = exe;
	}
	
	/**
	 * Get the executable file
	 * @return
	 */
	public String getExe() {
		return exe;
	}

	public void setLines(int lines) {
		this.lines = lines;
	}

	public int getLines() {
		return lines;
	}

}
